<template>
  <zm-panel
    :title="pTitle"
    :visible.sync="value"
    append-to-body
    size="large"
    :before-close="close"
    :close-on-click-modal="false"
  >
    <el-form
      :model="form"
      ref="form"
      :rules="Rules"
      label-width="140px"
      label-position="right"
    >
      <el-form-item label="开票日期：" prop="makeTime">
        <el-date-picker
          v-model="form.makeTime"
          type="date"
          placeholder="选择日期"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item label="开票笔数：" prop="makeType" v-if="!obj.id">
        <zm-data-radio
          v-model="form.makeType"
          :list="INVOICE_MAKETYPE"
          @change="makeTypeChange"
        ></zm-data-radio>
      </el-form-item>
      <zm-form-item label="归属业务员：" prop="salesmanId" ref="salesmanIdValidate">
        <!-- v-if="!loading" -->
        <el-cascader
          placeholder="归属业务员"
          :props="props"
          v-model="salesmanId"
          :options="accountList"
          clearable
          class="w200"
          @change="salesmanChange"
        ></el-cascader>
      </zm-form-item>

      <el-form-item label="关联客户：" prop="customerId" v-if="form.salesmanId">
        <zm-data-select
          v-model="form.customerId"
          api="getInvoiceCustomerList"
          :params="{ operatorId: form.salesmanId, status: obj.status }"
          placeholder="请选择关联客户"
          class="w200"
          @change="customerChange"
        ></zm-data-select>
      </el-form-item>

      <div v-for="(item, index) in form.invoice" :key="index">
        <el-form-item
          label="销售单号："
          :prop="'invoice.' + index + '.saleOrderNo'"
          :rules="Rules.saleOrderNo"
          class="vt"
        >
          <!-- <zm-input
            v-model="item.saleOrderNo"
            placeholder="请输入销售单号"
            class="w200 mb10 mr5"
          /> -->
          <zm-data-select
            v-model="item.saleOrderNo"
            :list="saleOrderOptions"
            label-name="orderNo"
            value-key="orderNo"
            placeholder="请选择销售单号"
            class="w200"
          ></zm-data-select>
          <!-- api="getInvoiceCustomerList"
            :params="{ operatorId: form.salesmanId, customerId: form.customerId }" -->
        </el-form-item>
        <el-form-item class="dib" label="销售单总价：" label-width="90px" v-if="item.saleOrderNo">
          <span>{{singleTotalPrice(item.saleOrderNo) || ''}}</span>
        </el-form-item>
        <el-form-item
          label="开票金额："
          label-width="90px"
          :prop="'invoice.' + index + '.amount'"
          :rules="Rules.amount"
          class="vt"
        >
          <zm-input
            v-model="item.amount"
            placeholder="请输入开票金额"
            class="w200 mb10 mr5"
          />
        </el-form-item>
        <el-form-item class="vt" label-width="0px" v-if="!obj.id">
          <div v-if="form.makeType === '2'" class="vm mr5">
            <zm-button
              @click="addInvoice(index)"
              t="add"
              v-if="index === 0 && form.invoice.length < 21"
            >
              新增
            </zm-button>
            <zm-button @click="delInvoice(index)" t="del" v-if="index !== 0">
              删除
            </zm-button>
          </div>
          <div class="vm">
            <zm-button
              @click="checkSaleOrderNo('more', index)"
              t="submit"
              v-if="index === 0"
            >
              {{ form.invoice.length > 1 ? "批量验证" : "验证" }}
            </zm-button>
          </div>
        </el-form-item>
      </div>
      <el-form-item label="销售单总额：">
        ￥{{ form.saleTotalPrice || "0" }}
      </el-form-item>
      <el-form-item label="实际应收：">
        ￥{{ form.realitySaleTotalPrice || "0" }}
      </el-form-item>
      <el-form-item label="已开票金额：">
        ￥{{ form.invoiceAmount || "0" }}
      </el-form-item>
      <!-- <el-form-item label="开票金额：" prop="amount" v-if="form.makeType === '1'">
        <zm-input
          v-model="form.amount"
          placeholder="请输入开票金额"
          class="w300"
        />
      </el-form-item> -->
      <el-form-item label="开票主体：" prop="invoiceMain">
        <zm-input
          v-model="form.invoiceMain"
          placeholder="请输入开票主体"
          class="w300"
        />
      </el-form-item>
      <el-form-item label="我方信息：" prop="ourInformation">
        <zm-data-select
          v-model="form.ourInformation"
          api="getOrderCompanyList"
          label-name="companyName"
          value-key="companyId"
          placeholder="我方信息"
          class="w200"
        ></zm-data-select>
      </el-form-item>
      <el-form-item label="票据类型：" prop="invoiceType">
        <zm-data-select
          v-model="form.invoiceType"
          k1="invoiceType"
          label-name="name"
          placeholder="票据类型"
          class="w200"
        ></zm-data-select>
      </el-form-item>
      <el-form-item label="纳税人识别号：" prop="identifyNumber">
        <zm-input
          v-model="form.identifyNumber"
          placeholder="请输入纳税人识别号"
          class="w300"
        />
      </el-form-item>
      <el-form-item label="发票号码：" prop="invoiceNumber">
        <span class="mr5">NO</span>
        <zm-input
          v-model="form.invoiceNumber"
          placeholder="请输入发票号码"
          class="w270"
        />
      </el-form-item>
      <el-form-item label="发票代码：" prop="invoiceCoding">
        <zm-input
          v-model="form.invoiceCoding"
          placeholder="请输入发票代码"
          class="w300"
        />
      </el-form-item>
      <el-form-item label="票据内容：" prop="billRemark">
        <zm-input
          type="textarea"
          v-model="form.billRemark"
          placeholder="请输入票据内容"
          :autosize="{ minRows: 3 }"
          :maxlength="500"
          class="w400"
        />
        <div class="mtb10">
          <el-button
            size="mini"
            type="primary"
            @click="
              () => {
                form.billRemark = '现代服务*电影票';
              }
            "
            class="vm mr10"
          >
            现代服务*电影票
          </el-button>
          <el-button
            size="mini"
            type="primary"
            @click="
              () => {
                form.billRemark = ' 烘焙食品蛋糕';
              }
            "
            class="vm"
          >
            烘焙食品蛋糕
          </el-button>
        </div>
      </el-form-item>
      <el-form-item label="地址、电话：" prop="address">
        <zm-input
          v-model="form.address"
          placeholder="请输入地址、电话"
          class="w300"
        />
      </el-form-item>
      <el-form-item label="开户行及账号：" prop="openingAccount">
        <zm-input
          v-model="form.openingAccount"
          placeholder="请输入客户开户行及账号"
          class="w300"
        />
      </el-form-item>
      <el-form-item label="上传发票相关附件：" prop="accessory">
        <zm-upload
          v-model="form.accessory"
          :http-request="fileUpload"
          accept=".rar,.zip,.doc,.docx,.pdf"
          :limit="1"
          :single-file-size="20"
        >
          <zm-button>选择附件</zm-button>
        </zm-upload>
      </el-form-item>
      <el-form-item label="备注信息：" prop="remark">
        <zm-input
          type="textarea"
          v-model="form.remark"
          placeholder="请输入备注信息"
          :autosize="{ minRows: 3 }"
          :maxlength="500"
          class="w400"
        />
      </el-form-item>
    </el-form>
    <div slot="footer" class="tr">
      <el-button size="small" @click="close">取消</el-button>
      <el-button size="small" type="primary" @click="submit">确定</el-button>
    </div>
  </zm-panel>
</template>

<script>
import ZmUpload from '@/components/ZmUpload/components/main'
import panelMixin from '@/mixins/panelMixin'
import { INVOICE_MAKETYPE } from '../const'
import { getAccountList } from '@/api/src/public'
import { getInfo, checkSaleOrder, update, create, getSaleOrderList } from '@/api/src/invoice'
import { uploadImg } from '@/api/src/upload'
import { dft } from '@/utils'
export default {
  components: { ZmUpload },
  mixins: [panelMixin],
  props: {
    props: {
      type: Object,
      default () {
        return {
          label: 'name',
          value: 'id',
          children: 'accountData'
        }
      }
    }
  },
  data () {
    return {
      INVOICE_MAKETYPE,
      dft,
      form: {
        status: '2', // 发票状态  1  待开票   2 已开票
        makeType: '1', // 开票笔数   1 单笔销售单开票   2  多笔销售单合并开票
        makeTime: dft('now', 'YYYY-MM-DD'),
        salesmanId: '',
        customerId: '',
        invoice: [{ saleOrderNo: '', amount: '' }],
        saleTotalPrice: '',
        realitySaleTotalPrice: '',
        invoiceAmount: '',
        amount: '',
        invoiceMain: '',
        ourInformation: '',
        invoiceType: '',
        identifyNumber: '',
        invoiceNumber: '',
        invoiceCoding: '',
        billRemark: '',
        address: '',
        openingAccount: '',
        accessory: '',
        remark: ''
      },
      salesmanId: [],
      accountList: [],
      saleOrderOptions: [],

      checkedSaveInvoice: '', // 验证后保存下销售单数据, 防止验证后修改销售单直接点确认

      loading: false,
      Rules: {
        makeTime: {
          required: true,
          message: '选择开票日期',
          trigger: 'change'
        },
        salesmanId: {
          required: true,
          message: '选择业务员',
          trigger: 'change'
        },
        customerId: {
          required: true,
          message: '选择客户',
          trigger: 'change'
        },
        saleOrderNo: {
          required: true,
          message: '输入销售单号',
          trigger: 'change'
        },
        saleTotalPrice: {
          required: true,
          message: '没有关联销售单总额',
          trigger: 'blur'
        },
        invoiceAmount: {
          required: true,
          message: '没有关联已开票金额',
          trigger: 'blur'
        },
        amount: {
          required: true,
          message: '请输入开票金额',
          trigger: ['change', 'blur']
        },
        invoiceMain: {
          required: true,
          message: '请输入开票主体',
          trigger: 'blur'
        },
        ourInformation: {
          required: true,
          message: '请选择我方信息',
          trigger: 'change'
        },
        invoiceType: {
          required: true,
          message: '请选择票据类型',
          trigger: 'change'
        },

        invoiceNumber: {
          required: true,
          message: '请输入发票号码',
          trigger: 'blur'
        },
        billRemark: {
          required: true,
          message: '请输入票据内容',
          trigger: 'blur'
        }
      }
    }
  },
  computed: {
    pTitle () {
      return this.obj.id ? '发票信息编辑' : '发票信息新增'
    },
    singleTotalPrice () {
      return (saleNo) => {
        const item = this.saleOrderOptions.find(item => item.orderNo === saleNo) || {}
        return item.saleTotalPrice
      }
    }
  },
  created () {
  },
  mounted () {
    this.init()
    if (this.obj.id) {
      this.getInfo()
    }
  },
  methods: {
    async init () {
      this.accountList = await getAccountList()
    },
    async getInfo () {
      const form = await getInfo({ id: this.obj.id })
      this.form = Object.assign({}, this.form, form)
      this.form.makeTime = this.dft('now', 'YYYY-MM-DD')

      this.$set(
        this.form,
        'invoiceNumber',
        this.form.invoiceNumber.replace(/NO/g, '')
      )
    },
    resetFields () {
      this.form = Object.assign({}, this.form, {
        // salesmanId: '',
        // customerId: '',
        invoice: [{ saleOrderNo: '', amount: '' }],
        saleTotalPrice: '',
        realitySaleTotalPrice: '',
        invoiceAmount: '',
        amount: '',
        invoiceMain: '',
        ourInformation: '',
        invoiceType: '',
        identifyNumber: '',
        invoiceNumber: '',
        invoiceCoding: '',
        billRemark: '',
        address: '',
        openingAccount: '',
        accessory: '',
        remark: ''
      })
    },
    makeTypeChange (val) {
      this.resetFields()
      this.form.salesmanId = ''
      this.form.customerId = ''
      this.salesmanId = []
      this.saleOrderOptions = []
      // this.$refs['form'].clearValidate()
    },
    async salesmanChange (val) {
      this.loading = true
      this.resetFields()
      this.form.customerId = ''
      this.saleOrderOptions = []
      if (val.length === 0) {
        this.form.salesmanId = ''
        this.loading = false
        return
      }
      this.$nextTick(() => {
        this.$set(this.form, 'salesmanId', this.salesmanId[1])
        this.$refs['salesmanIdValidate'].clearValidate()
      })
    },
    async customerChange (val) {
      // 客户切换 销售单要重新渲染
      this.loading = true
      this.resetFields()
      this.saleOrderOptions = []

      if (val.length === 0) {
        this.saleOrderOptions = []
        this.loading = false
        return
      }
      this.saleOrderOptions = await getSaleOrderList({operatorId: this.form.salesmanId, customerId: this.form.customerId})
      this.$nextTick(() => {
        this.loading = false
      })
    },
    async checkSaleOrderNo (type, index) {
      let res = {}
      const _arr = this.form.invoice.filter(item => item.saleOrderNo)
      const _amount = this.form.invoice.filter(item => item.amount)

      if (_arr.length !== this.form.invoice.length || _amount.length !== this.form.invoice.length) {
        this.$message.warning('请填写完整销售单')
        return
      }
      const str = _arr.map(item => {
        return item.saleOrderNo
      })

      let _adding = 0
      _adding = _arr.reduce((prev, next) => {
        return +prev + +next.amount
      }, 0)

      this.$set(this.form, 'amount', _adding)

      res = await checkSaleOrder({ orderNo: str.join(',') })
      this.$message.success('验证通过')

      this.form.customerId = res.customerList.id // 关联客户
      this.form.saleTotalPrice = res.saleTotalPrice // 销售总额
      this.form.invoiceAmount = res.invoiceAmount // 已开票金额
      this.form.identifyNumber = res.customerList.taxCode || this.form.identifyNumber // 纳税人识别号
      this.form.invoiceMain = res.invoiceCompany || this.form.invoiceMain // 开票主体
      this.form.realitySaleTotalPrice = res.realitySaleTotalPrice // 实际应收
      this.form.address =
        res.customerList.address + ' ' + res.customerList.mobile // 客户地址/电话
      this.form.ourInformation = res.saleList.length > 0 && res.saleList[0].companyType // 我方信息
      this.form.invoiceType = res.saleList.length > 0 && res.saleList[0].invoiceType // 票据类型

      this.checkedSaveInvoice = JSON.parse(JSON.stringify(this.form.invoice)).map(item => {
        return item.saleOrderNo
      }) // 保存验证后的销售单, 防止验证后修改销售单直接确认
    },
    addInvoice (index) {
      this.form.invoice.push({ saleOrderNo: '', amount: '' })
    },
    delInvoice (index) {
      this.form.invoice.splice(index, 1)
    },
    async submit () {
      let _valid = false
      this.$refs.form.validate(valid => {
        _valid = valid
      })
      if (!_valid) {
        return
      }

      const _tempSaveInvoice = JSON.parse(JSON.stringify(this.checkedSaveInvoice))
      const _tempArr = this.form.invoice.map(item => {
        return item.saleOrderNo
      })

      if (_tempSaveInvoice.toString() !== _tempArr.toString()) { // 再次确认销售单是否验证后的销售单号
        this.$message.warning('请先验证再确认')
        return
      }

      const _arr = this.form.invoice.filter(item => item.saleOrderNo)
      let _adding = 0
      _adding = _arr.reduce((prev, next) => {
        return +prev + +next.amount
      }, 0)

      this.$set(this.form, 'amount', _adding)

      if (+this.form.amount > +this.form.saleTotalPrice - +this.form.invoiceAmount) {
        this.$confirm('开票金额已超过销售金额减去已开票金额,确定开票?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
          const _api = this.obj.id ? update : create
          await _api(this.form).then(r => {
            this.$message.success(`${this.pTitle}成功`)
            this.$emit('after')
            this.close()
          })
        }).catch(() => {

        })
      } else {
        const _api = this.obj.id ? update : create
        await _api(this.form).then(r => {
          this.$message.success(`${this.pTitle}成功`)
          this.$emit('after')
          this.close()
        })
      }
    },
    async fileUpload (data) {
      let params = new FormData()
      params.append('fileData', data.file)
      // 上传接口对接
      const res = await uploadImg(params)
      // this.form = { ...this.form, ...{ accessory: res.url } }
      this.form.accessoryName = res.name
      return res.url
    }
  }
}
</script>
<style lang="scss" scoped>
/deep/ .el-form {
  .el-form-item {
    margin-bottom: 22px;
  }
}
// .textBottom {
//   vertical-align: text-bottom;
//   margin-bottom: 0px !important;
// }
</style>
